package com.hhsjdesign.dynamicui.core.widgetimpl.businesswidget.adapter

import android.content.Context
import android.view.ViewGroup
import android.widget.GridLayout
import androidx.annotation.IntRange
import androidx.recyclerview.widget.RecyclerView
import com.hhsjdesign.dynamicui.utils.BusinessViewCreatorFactory
import com.hhsjdesign.dynamicui.businessdata.IViewable
import com.hhsjdesign.dynamicui.utils.BusinessViewCreator
import com.hhsjdesign.dynamicui.core.property.viewdata.ItemViewData

/**
 * 适配器，
 * 1，context
 * 2，itemViewWidget用于创建子视图模板
 * 3，
 */
class GridAdapter(
    val context: Context,
    val itemViewType: String?,
    val itemViewData: ItemViewData?,
    val businessType: String,

    val itemDataList: MutableList<IViewable<*>>,
    @IntRange(from = 1)
    val row: Int = 1,
    @IntRange(from = 1)
    val column: Int = 1
) : RecyclerView.Adapter<WidgetHolder<*>>() {

    private val viewHolder: BusinessViewCreator<*>?

    init {
        viewHolder = BusinessViewCreatorFactory.makeViewHolder(businessType)
    }

    override fun getItemId(position: Int): Long {
        return itemDataList[position].hashCode().toLong()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WidgetHolder<*> {
        //创建gridLayout视图
        val pageView = GridLayout(context)
        pageView.rowCount = row
        pageView.columnCount = column
        for (i in 0 until row * column) {
            pageView.addView(itemViewData!!.createView(context))
        }
        return WidgetHolder(pageView, viewHolder!!)
    }

    override fun onBindViewHolder(holder: WidgetHolder<*>, position: Int) {
        holder.businessHolder.bindDataAndEvent(
            holder.itemView,
            itemDataList[position],
            itemViewType,
            businessType,
            itemViewData
        )
    }

    override fun getItemCount(): Int {
        return itemDataList.size / (row * column)
    }

}